package com.galaxy.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.galaxy.common.dao.BaseDaoI;
import com.galaxy.common.util.list.ListUtil;
import com.galaxy.common.web.page.DataGrid;
import com.galaxy.common.web.page.Json;
import com.galaxy.common.web.page.LoginInfoSession;
import com.galaxy.system.entity.ModuleEntity;
import com.galaxy.system.entity.RoleEntity;
import com.galaxy.system.entity.UserDetailEntity;
import com.galaxy.system.entity.UserEntity;
import com.galaxy.system.service.UserServiceI;
import com.galaxy.system.web.form.UserForm;

@Service
@Transactional
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private BaseDaoI<UserEntity> basedaoUser;
	
	@Autowired
	private BaseDaoI<RoleEntity> basedaoRole;
	
	@Autowired
	private BaseDaoI<ModuleEntity> basedaoModule;

	@Override
	public Json save(UserForm form) {
		Json j = new Json();
		try {
			UserEntity entity = new UserEntity();
			BeanUtils.copyProperties(form, entity, new String[] { "created" });

			//详细信息
			UserDetailEntity ude = new UserDetailEntity() ;
			BeanUtils.copyProperties(form, ude, new String[] { "id" });
			entity.setUser_detail(ude) ;
			
			this.basedaoUser.save(entity);
			
			j.setMsg("创建成功！") ;
			j.setStatus(true) ;
		} catch (BeansException e) {
			j.setMsg("创建失败！") ;
		}
		return j;
	}
	
	@Override
	public Json addOrUpdate(UserForm form) {
		Json j = new Json();
		try {
			UserEntity entity = new UserEntity();
			BeanUtils.copyProperties(form, entity, new String[] { "created" });

			UserDetailEntity ude = new UserDetailEntity() ;
			BeanUtils.copyProperties(form, ude);
			entity.setUser_detail(ude) ;
			
			this.basedaoUser.saveOrUpdate(entity);
			
			j.setMsg("创建成功！") ;
			j.setStatus(true) ;
		} catch (BeansException e) {
			j.setMsg("创建失败！") ;
		}
		return j;
	}

	@Override
	public Json delete(UserForm form) {
		Json j = new Json();
		try {
			if(null != form.getIds() && !"".equals(form.getIds())) {
				String[] ids = form.getIds().split(",") ;
				for (String id : ids) {
					UserEntity o = this.basedaoUser.get(UserEntity.class, id);
					this.basedaoUser.delete(o) ;
				}
				j.setMsg("删除成功！") ;
				j.setStatus(true) ;
			}
		} catch (BeansException e) {
			j.setMsg("删除失败！") ;
		}
		return j;
	}
	

	@Override
	public Json edit(UserForm form) {
		Json j = new Json();
		try {
			UserEntity entity = this.basedaoUser.get(UserEntity.class, form.getId());
			
			if(entity != null) {
				form.setCreated(new Date()) ;
				BeanUtils.copyProperties(form, entity);
				
				UserDetailEntity user_detail = new UserDetailEntity() ;
				BeanUtils.copyProperties(form, user_detail, new String[] { "id" });
				
				entity.setUser_detail(user_detail) ;
				
				this.basedaoUser.update(entity) ;
			}
			
			j.setMsg("编辑成功！") ;
			j.setStatus(true) ;
		} catch (BeansException e) {
			j.setMsg("编辑失败！") ;
		}
		return j;
	}
	

	@Override
	public UserForm get(String id) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		UserEntity entity = this.basedaoUser.get("select t from UserEntity t where t.id = :id", params);
		
		UserForm form = new UserForm();
		
		if(null != entity) {
			BeanUtils.copyProperties(entity, form);
			if(null != entity.getUser_detail()) {
				BeanUtils.copyProperties(entity.getUser_detail(), form, new String[] { "id" });
			}
		}
		return form ;
	}
	
	@Override
	public UserForm get(UserForm form) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = "select t from UserEntity t where 1=1";
		hql = addWhere(hql, form, params) + addOrdeby(form);
		
		UserEntity entity = this.basedaoUser.get(hql, params) ;
		if(null != entity) {
			UserForm pform = new UserForm();
			BeanUtils.copyProperties(entity, pform);
			
			UserDetailEntity user_detail = entity.getUser_detail() ;
			if(null != user_detail) {
				BeanUtils.copyProperties(user_detail, pform, new String[] { "id" });
			}
			return pform;
		} else {
			return null ;
		}
	}

	@Override
	public Json set_permit(UserForm form) {
		Json j = new Json();
		if (form.getIds() != null && !"".equalsIgnoreCase(form.getIds())) {
			List<RoleEntity> roles = new ArrayList<RoleEntity>();
			if (form.getRoleIds() != null && form.getRoleIds().length() > 0) {
				for (String roleId : form.getRoleIds().split(",")) {
					roles.add(this.basedaoRole.get(RoleEntity.class, roleId));
				}
			}
			for (String id : form.getIds().split(",")) {
				if (id != null && !id.equalsIgnoreCase("")) {
					UserEntity t = this.basedaoUser.get(UserEntity.class, id);
					t.setRole_permit(new HashSet<RoleEntity>(roles));
				}
			}
		}
		j.setMsg("分配角色成功！") ;
		j.setStatus(true) ;
		
		return j;
	}
	
	@Override
	public DataGrid datagrid(UserForm form) {
		
		List<UserForm> forms = new ArrayList<UserForm>();
		List<UserEntity> users = this.find(form) ;
		if (null != users && users.size() > 0) {
			for (UserEntity i : users) {
				UserForm uf = new UserForm();
				BeanUtils.copyProperties(i, uf);
				if(null != i.getUser_detail()) {
					BeanUtils.copyProperties(i.getUser_detail(), uf, new String[] { "id" });
				}
				forms.add(uf);
			}
		}
		
		
		DataGrid datagrid = new DataGrid();
		datagrid.setTotal(this.total(form));
		datagrid.setRows(forms);
		return datagrid;
	}


	private List<UserEntity> find(UserForm form) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = "select t from UserEntity t where 1=1";
		hql = addWhere(hql, form, params) + addOrdeby(form);
		return this.basedaoUser.find(hql, params, form.getPage(), form.getRows());
	}

	private String addOrdeby(UserForm form) {
		String orderString = "";
		if (form.getSort() != null && form.getOrder() != null) {
			orderString = " order by " + form.getSort() + " " + form.getOrder();
		}
		return orderString;
	}

	public Long total(UserForm form) {
		Map<String, Object> params = new HashMap<String, Object>();

		String hql = "select count(*) from UserEntity t where 1=1";

		hql = addWhere(hql, form, params);

		return this.basedaoUser.count(hql, params);
	}

	private String addWhere(String hql, UserForm form, Map<String, Object> params) {
		if (null != form) {
			/*if (form.getTruename() != null && !"".equals(form.getTruename())) {
				hql += " and t.name like :name";
				params.put("name", "%%" + form.getTruename() + "%%");
			}
			if (form.getAccount() != null && !"".equals(form.getAccount())) {
				hql += " and t.account like :account";
				params.put("account", "%%" + form.getAccount() + "%%");
			}
			if (form.getSex() != null && !"".equals(form.getSex())) {
				hql += " and t.sex like :sex";
				params.put("sex", "%%" + form.getSex() + "%%");
			}
			if (form.getTel() != null && !"".equals(form.getTel())) {
				hql += " and t.tel like :tel";
				params.put("tel", "%%" + form.getTel() + "%%");
			}
			if (form.getEmail() != null && !"".equals(form.getEmail())) {
				hql += " and t.email like :email";
				params.put("email", "%%" + form.getEmail() + "%%");
			}
			if (form.getOrgname() != null && !"".equals(form.getOrgname())) {
				hql += " and t.orgname like :orgname";
				params.put("orgname", "%%" + form.getOrgname() + "%%");
			}
			if (form.getOnlineState() != null && !"".equals(form.getOrgname())) {
				hql += " and t.onlineState=:onlineState";
				params.put("onlineState", form.getOnlineState());
			}*/
		}
		return hql;
	}

	@Override
	public UserForm getPermission(UserForm form) {
		UserForm r = new UserForm();
		
		UserEntity t = this.basedaoUser.get("select distinct t from UserEntity t left join fetch t.role_permit role where t.id = '" + form.getId() + "'");
		
		if (t != null) {
			BeanUtils.copyProperties(t, r);
			Set<RoleEntity> s = t.getRole_permit();
			if (s != null && !s.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (RoleEntity tr : s) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += tr.getId();
					names += tr.getName();
				}
				
				r.setRoleIds(ids);
				r.setRoleNames(names);
			}
		}
		return r;
	}
	
	
	@Override
	public UserForm get_module_permit(UserForm form) {
		UserForm r = new UserForm();

		UserEntity t = this.basedaoUser.get("select distinct t from UserEntity t left join fetch t.modules_permit m where t.id = '" + form.getId() + "'");
		
		if (t != null) {
			BeanUtils.copyProperties(t, r);
			Set<ModuleEntity> s = t.getModules_permit() ;
			if (s != null && !s.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (ModuleEntity tr : s) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					System.out.println(tr.getModuleName());
					ids += tr.getId();
					names += tr.getModuleName() ;
				}

				r.setModuleIds(ids);
				r.setModuleNames(names);
			}
		}
		return r;
	}
	
	
	@Override
	public Json set_module_permit(UserForm form) {
		Json j = new Json();
		try {
			UserEntity user = this.basedaoUser.get(UserEntity.class, form.getId()) ;
			
			if(form.getModuleIds() != null && !"".equalsIgnoreCase(form.getId())) {
				String ids = "";
				boolean b = false;
				for (String id : form.getModuleIds().split(",")) {
					if (b) {
						ids += ",";
					} else {
						b = true;
					}
					ids += "'" + id + "'";
				}
				user.setModules_permit(new HashSet<ModuleEntity>(this.basedaoModule.find("select distinct t from ModuleEntity t where t.id in (" + ids + ")"))) ;
			} else {
				user.setModules_permit(null) ;
			}
				j.setStatus(true);
				j.setMsg("资源授权成功!");

		} catch (Exception e) {
			j.setMsg("资源授权失败!");
		}
		return j;
	}
	
	@Override
	public UserForm login(UserForm user) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("account", user.getAccount());
		params.put("password", user.getPassword());
		UserEntity t = this.basedaoUser.get("from UserEntity t where t.account = :account and t.password = :password", params);
		if (t != null) {
			BeanUtils.copyProperties(t, user);
			
			UserDetailEntity user_detail = t.getUser_detail() ;
			if(null != user_detail) {
				BeanUtils.copyProperties(user_detail, user, new String[]{"id"});
				user.setDept_id(user_detail.getId()) ;
			}
		} else {
			user = null;
		}
		return user;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> MyPermission(String id, String account) throws Exception {
		List<String> resourceList = new ArrayList<String>();
		
		//超级管理员默认拥有所有操作权限
		if("admin".equals(account)) {
			String hql = "select t from ModuleEntity t where 1=1 and t.linkUrl != '' " ;
			List<ModuleEntity> module = this.basedaoModule.find(hql) ;
			for (ModuleEntity m : module) {
				resourceList.add(m.getLinkUrl());
			}
			
		} else {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("id", id);
			UserEntity t = this.basedaoUser.get("select t from UserEntity t join fetch t.role_permit role where t.id = :id", params);
			if (t != null) {
				
				Set<RoleEntity> roles = t.getRole_permit() ;
				if (roles != null && !roles.isEmpty()) {
					for (RoleEntity role : roles) {
						Set<ModuleEntity> modules = role.getModules();
						if (modules != null && !modules.isEmpty()) {
							for (ModuleEntity resource : modules) {
								if (resource != null && resource.getLinkUrl() != null && !"".equals(resource.getLinkUrl())) {
									resourceList.add(resource.getLinkUrl());
								}
							}
						}
					}
				}
				
				Set<ModuleEntity> modules = t.getModules_permit() ;
				if(null != modules && !modules.isEmpty()) {
					for (ModuleEntity module : modules) {
						if (module != null && module.getLinkUrl() != null && !"".equals(module.getLinkUrl())) {
							resourceList.add(module.getLinkUrl());
						}
					}
				}
			}
		}
		
		return ListUtil.removeDuplicate(resourceList);
	}
	
	@Override
	public boolean editCurrentUserPwd(LoginInfoSession sessionInfo, String oldPwd, String pwd) {
		UserEntity u = this.basedaoUser.get(UserEntity.class, sessionInfo.getUser().getId());
		if (u.getPassword().equalsIgnoreCase(oldPwd)) {
			u.setPassword(pwd);
			return true;
		}
		return false;
	}

}
